package search;

import org.apache.commons.codec.binary.Base64;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class Bing {
  public static String search(String query) throws Exception {
    String bingUrl = "https://api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27" + java.net.URLEncoder.encode(query,"UTF-8") +"%27&Market=%27en-GB%27" + "&$format=JSON";
    String accountKey = "GShrZElyVNrCQEEgqD7YDmAYlsEcGqztfhhJFOiTu54=";
    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);
    
    URL url = new URL(bingUrl);
    URLConnection urlConnection = url.openConnection();
    String s1 = "Basic " + accountKeyEnc;
    urlConnection.setRequestProperty("Authorization", s1);
    BufferedReader in = new BufferedReader(new InputStreamReader(
        urlConnection.getInputStream()));
    String inputLine;
    String answer = "";
    while ((inputLine = in.readLine()) != null)
      answer = answer + inputLine;
    in.close();
    return answer;
  }
}
